package com.lft12.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Function: 		A {@code TestLock} 测试 Lock 锁<br/>
 * Reason:   		ADD REASON.<br/>
 * Date:            2021-01-28 13:12<br/>
 * <p>
 * Class Name:      TestLock<br/>
 * Package Name:    com.lft12.lock<br/>
 * @author Laifengting / E-mail:laifengting@foxmail.com
 * @version 1.0.0
 * @since JDK 8
 */
public class TestLock {
	public static void main(String[] args) {
		TestLock2 testLock2 = new TestLock2();
		new Thread(testLock2, "线程1").start();
		new Thread(testLock2, "线程2").start();
		new Thread(testLock2, "线程3").start();
	}
}

class TestLock2 implements Runnable {
	int ticketNums = 10;
	
	// 定义锁
	Lock lock = new ReentrantLock();
	
	@Override
	public void run() {
		while (true) {
			lock.lock();
			try {
				if (ticketNums > 0) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println(ticketNums--);
				} else {
					break;
				}
			} finally {
				lock.unlock();
			}
			
		}
	}
}